using System;
using System.Collections.Generic;
using FrameWork;
using UnityEngine;
using UnityEngine.Tilemaps;

namespace FrameWork.TileMapManager
{
     /// <summary>
     /// 序列化文件
     /// 用来配置作物生长状态等等
     /// </summary>
     [CreateAssetMenu(fileName = "CropModel", menuName = "Tile Map/Crop Model")]

    public class CropModel : ScriptableObject
    {
        [field: SerializeField] public string cropName;           // 作物类型，唯一
        [SerializeField] public TileBase[] cropSprites;           // 生长图片
    }

    public class CropData
    {
        public CropModel CropModel { get; private set; }
        public Vector3Int Position { get; private set; } // 作物在瓦片地图上的位置
        public int GrowthStage { get; private set; }     // 生长阶段
        private bool isWater;                            // 是否浇水
        private string cropName;                         // 作物标签
        private bool isCanHarvestCrop;                   // 是否可以收获

        public CropData(CropModel cropModel, Vector3Int position, int growthStage, string cropName)
        {
            CropModel = cropModel;
            Position = position;
            GrowthStage = growthStage;
            this.cropName = cropName;

            // 变量初始化
            isWater = true;
            isCanHarvestCrop = false;

            // 事件注册，每天变化，清空浇水状态
            EventSystem.Instance.AddListener(EventName.EVENT_TIME_UPDATE, () => { isWater = false; });
        }

        /// <summary>
        /// 浇水
        /// </summary>
        public void WaterCrop()
        {
            // 如果没有浇水，更新生长状态
            if (!isWater)
            {
                GrowthStage += 1;
                Debug.Log("浇水成功，当前生长阶段" + GrowthStage);
                // 大于三阶段，固定阶段为四阶段，并且设置可以收获
                if (GrowthStage > 3)
                {
                    GrowthStage = 4;
                    isCanHarvestCrop = true;
                }
                
                isWater = true;
            }
            
            Debug.Log("当前生长阶段" + GrowthStage);

            // 触发系统广播事件
            EventSystem.Instance.EventTrigger(EventName.EVENT_SYSTEM_ADD_TIPS, $"给位置 {Position} 的作物浇水");
        }

        /// <summary>
        /// 收获作物
        /// </summary>
        public void HarvestCrop()
        {
            // 生成作物
            if(!isCanHarvestCrop)
                return;
            CropManager.Instance.SpawnCrop(cropName);
        }
        
        /// <summary>
        /// 获取当前生长状态的图片
        /// </summary>
        /// <returns></returns>
        public TileBase GetCropSprite()
        {
            return CropModel.cropSprites[GrowthStage - 1];
        }
    }
}